# -*- coding: utf-8 -*-
# @Time    : 2020/11/10 20:59
# @Author  : DuJiabao
# @File    : SingleLinkList.py
# @Description : This is a file of SingleLinkList. 这是一个单链表文件。
from LinkList.Node import Node


class SingleLinkList(object):
    """
    SingleLinkList class
    """

    def __init__(self):
        self.head = Node(None)  # 头结点
        self.len = 0

    def __len__(self):
        return self.len

    def isEmpty(self):
        return self.head.next is None

    def isLast(self, p):
        return p.next is None

    def find(self, element):
        """
        Find the node contains the element in this LinkList
        :param element: element
        :return: node
        """
        P = self.head.next
        while P is not None:
            if P.element == element:
                return P
            P = P.next
        return None

    def findPrevious(self, element):
        """
        Find the previous node of the node that contains the element.
        :param element: element
        :return: node
        """
        P = self.head
        while P.next is not None:
            if P.next.element == element:
                return P
            P = P.next
        return None

    def delete(self, element):
        """
        Delete the node contains the element.
        :param element: element
        :return: True/False
        """
        P = self.findPrevious(element)
        if P is None:
            return False
        P.next = P.next.next
        self.len -= 1
        return True

    def insert(self, position, element):
        """
        Insert the element to the position of this LinkList.
        :param position: position
        :param element: element
        :return: True/False
        """
        node = Node(element)
        count = -1
        P = self.head
        while count < position - 1:
            if P.next is None:
                break
            P = P.next
            count += 1

        if count == position - 1:
            node.next = P.next
            P.next = node
            self.len += 1
            return True
        else:
            return False

    def pop(self):
        """
        An generator pop the node of this LinkList. (From head to tail)
        :return: node
        """
        P = self.head
        while P.next:
            P = P.next
            yield P
            self.len -= 1

    def show(self):
        """
        Show all node's element of this LinkList. (From head to tail)
        :return:
        """
        P = self.head
        while P.next:
            P = P.next
            print(P.element, end=" ")
        print("")


if __name__ == '__main__':
    sgll = SingleLinkList()
    print(sgll.insert(0, 0))
    print(sgll.insert(0, 1))
    print(sgll.insert(2, 3))
    print(sgll.insert(1, 4))
    print(sgll.insert(4, 5))
    sgll.show()
    # print(sgll.delete(5), sgll.isEmpty(), sgll.find(0), sgll.findPrevious(0))
    # sgll.show()
    print(sgll.find(1))
